package com.wentao.mall.api

import com.aliyun.oss.ClientConfiguration
import com.aliyun.oss.OSSClient
import com.aliyun.oss.common.auth.DefaultCredentialProvider
import com.aliyun.oss.common.utils.BinaryUtil
import com.aliyun.oss.model.MatchMode
import com.aliyun.oss.model.PolicyConditions
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.sql.Date

@RestController
class OssController {
    @RequestMapping(value = ["/admin/oss/policy", "/api/oss/policy"])
    fun generatePostPolicy(): PostPolicy {
        val accessId = "9hwWaqijK8gFN6gQ" // 请填写您的AccessKeyId。
        val accessKey = "gO3qp7EOXm0s92qy4j3rDyW2ja2BTK" // 请填写您的AccessKeySecret。
        val endpoint = "oss-cn-shanghai.aliyuncs.com" // 请填写您的 endpoint。
        val bucket = "zy46" // 请填写您的 bucketname 。
        val host = "https://$bucket.$endpoint" // host的格式为 bucketname.endpoint
        val dir = "mall/"

        val credentialProvider = DefaultCredentialProvider(accessId, accessKey)
        val config = ClientConfiguration()
        config.isRequestTimeoutEnabled
        val client = OSSClient(endpoint, credentialProvider, null)
        val expireEndTime = System.currentTimeMillis() + 30 * 60 * 1000 // 过期时间半小时
        val expiration = Date(expireEndTime)
        val policyConds = PolicyConditions()
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000)
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir)

        val postPolicy: String = client.generatePostPolicy(expiration, policyConds)
        val binaryData = postPolicy.toByteArray(charset("utf-8"))
        val encodedPolicy = BinaryUtil.toBase64String(binaryData)
        val postSignature = client.calculatePostSignature(postPolicy)

        return PostPolicy(
            accessId = accessId,
            policy = encodedPolicy,
            signature = postSignature,
            dir = dir,
            host = host,
            expire = expireEndTime / 1000
        )

    }

    data class PostPolicy(
        val accessId: String,
        val policy: String,
        val signature: String,
        val dir: String,
        val host: String,
        val expire: Long

    )
}